package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.dto.WxDecryptedUserInfo;
import com.ruoyi.system.domain.dto.WxUserInfo;
import com.ruoyi.system.domain.vo.request.WxLoginRequest;
import com.ruoyi.system.service.WxProcessor;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author czg
 * @date 2021/9/11 2:22 下午
 */
@Api(tags = "微信小程序登录授权")
@RestController
@RequestMapping("/api/wx")
public class WxController {


    private static final Logger logger = LoggerFactory.getLogger(WxController.class);


    @Autowired
    WxProcessor wxProcessor;


    @PostMapping("/login")
    @ApiOperation("小程序登录")
    public AjaxResult<WxDecryptedUserInfo> login(@RequestBody WxLoginRequest request) throws Exception {

        //获取微信用户唯一标识openid
        WxUserInfo wxUserInfo = wxProcessor.queryXcxUserInfoByJscode(request.getCode());
        if (null == wxUserInfo || StringUtils.isBlank(wxUserInfo.getOpenid())) {
            throw new Exception("WX_CODE2SESSION_ERROR");
        }
        //解密微信基础信息
        WxDecryptedUserInfo userInfo = wxProcessor.decodeUser(request.getEncryptedData(), request.getIv(), wxUserInfo.getSession_key());

        logger.info("小程序用户信息{}", JSON.toJSONString(userInfo));

        return AjaxResult.success(userInfo);
    }


    @GetMapping("/getPhone")
    @ApiOperation("小程序获取用户手机号")
    public AjaxResult<String> getPhone(@RequestBody WxLoginRequest request) {
        //解密获取手机号
        WxDecryptedUserInfo userInfo = wxProcessor.decodeUserPhone(request.getEncryptedData(), request.getIv(), "");
        logger.info("小程序用户信息{}", JSON.toJSONString(userInfo));
        return AjaxResult.success(userInfo.getPhoneNumber());
    }

}
